import React, { Component } from "react";
//css
import "./Login.css";
//组件
import "antd/dist/antd.css";
import { Form, Input, Button, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { login } from "../../api/login";

export default class Login extends Component {
  onFinish = async (values) => {
    console.log("Success:", values);
    try {
      let { data: res } = await login(values);
      console.log(res);
      if (res && res.code === 200) {
        message.success(res.message);
        window.sessionStorage.setItem("user_name", res.data.user.user_name);
        console.log(res);
        this.props.history.replace("/");
        //将登录成功之后的token,保存到客户端的sessionStorage中
        window.sessionStorage.setItem("token", res.data.user.token);
      } else {
        message.error(res.message);
      }
    } catch (err) {
      message.error("登录连接失败，请检查网络");
    }
  };

  render() {
    return (
      <div className="login">
        <div className="login_content">
          <span className="login_title">淮安预约管理系统</span>
          <div className="login_box">
            <Form
              name="normal_login"
              className="login-form"
              initialValues={{ remember: true }}
              onFinish={this.onFinish}
            >
              <Form.Item
                name="user_name"
                rules={[
                  { required: true, message: "用户名不能为空" },
                  //   { min: 2, message: "用户名不能小于2位" },
                  //   { max: 8, message: "密码不能大于8位" },
                  ({ getFieldValue }) => ({
                    validator(_, value) {
                      if (value.length < 2 || value.length > 8) {
                        return Promise.reject("用户名不能小于2位");
                      } else {
                        return Promise.resolve();
                      }
                    },
                  }),
                ]}
              >
                <Input
                  prefix={<UserOutlined className="site-form-item-icon" />}
                  placeholder="请输入用户名"
                />
              </Form.Item>

              <Form.Item
                name="pswd"
                rules={[
                  { required: true, message: "密码不能为空" },
                  { min: 6, message: "密码不能小于6位" },
                  { max: 12, message: "密码不能大于12位" },
                ]}
              >
                <Input
                  prefix={<LockOutlined className="site-form-item-icon" />}
                  type="password"
                  placeholder="请输入密码"
                />
              </Form.Item>

              <Form.Item>
                <Button
                  block
                  type="primary"
                  htmlType="submit"
                  className="login-form-button"
                >
                  登陆
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    );
  }
}
